package com.module.compose.base.utils

import android.content.Context
import android.content.SharedPreferences
import com.module.compose.base.App
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * SP类获取一个AppSharedPreferences实例
 */
class SP(
    private val sp: SharedPreferences =
        App.getContext()
            .getSharedPreferences("AppSharedPreferences", Context.MODE_PRIVATE)
) : SharedPreferences by sp

/**
 * 存取Boolean类型数据
 */
class BooleanSP(private val key: String) : ReadWriteProperty<Any, Boolean> {
    private val sp by lazy { SP() }

    override fun getValue(thisRef: Any, property: KProperty<*>): Boolean {
        return sp.getBoolean(key, false)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Boolean) {
        sp.edit().putBoolean(key, value).apply()
    }
}

/**
 * 存取Float类型数据
 */
class FloatSP(private val key: String) : ReadWriteProperty<Any, Float> {
    private val sp by lazy { SP() }

    override fun getValue(thisRef: Any, property: KProperty<*>): Float {
        return sp.getFloat(key, 0f)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Float) {
        sp.edit().putFloat(key, value).apply()
    }
}

/**
 * 存取Integer类型数据
 */
class IntegerSP(private val key: String) : ReadWriteProperty<Any, Int> {
    private val sp by lazy { SP() }

    override fun getValue(thisRef: Any, property: KProperty<*>): Int {
        return sp.getInt(key, 0)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) {
        sp.edit().putInt(key, value).apply()
    }
}

/**
 * 存取Long类型数据
 */
class LongSP(private val key: String) : ReadWriteProperty<Any, Long> {
    private val sp by lazy { SP() }

    override fun getValue(thisRef: Any, property: KProperty<*>): Long {
        return sp.getLong(key, 0L)
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: Long) {
        sp.edit().putLong(key, value).apply()
    }
}

/**
 * 存取String类型数据
 */
class StringSP(private val key: String) : ReadWriteProperty<Any, String> {
    private val sp by lazy { SP() }

    override fun getValue(thisRef: Any, property: KProperty<*>): String {
        return sp.getString(key, "")!!
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
        sp.edit().putString(key, value).apply()
    }
}